package cn.cms.listener;

import cn.cms.annotation.SystemLogAnno;
import cn.cms.constants.Constants;
import cn.cms.webcommon.LocalContextFactory;
import cn.cms.dao.SysLogDao;
import cn.cms.model.SysLog;
import cn.cms.model.SysUser;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;

public class SessionListener implements HttpSessionListener {

    private static Logger logger = LoggerFactory.getLogger(SessionListener.class);

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        logger.info("HttpSession创建>>>>>>>>>>>>>>>> " + session.getId() + "|" + session.getCreationTime());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        logger.info("HttpSession销毁>>>>>>>>>>>>>>>> " + session.getId() + "|" + session.getCreationTime());
        String sessionId = session.getId();
        SysUser loginUser = (SysUser) session.getAttribute(Constants.SESSION_KEY);
        if (loginUser != null) {
            this.saveLogoutLog(loginUser, sessionId);
        }
    }

    private void saveLogoutLog(SysUser user, String sessionId) {
        Date date = new Date();
        // 登录时长
        Long loginTime = date.getTime() - user.getLoginDate().getTime();
        String onLineTime = loginTime / (1000 * 60 * 60) + "小时" + loginTime % (1000 * 60 * 60) / (1000 * 60) + "分钟" + loginTime % (1000 * 60 * 60) % (1000 * 60) / (1000) + "秒";
        logger.info("正常退出系统(" + sessionId + ")，在线时长：" + onLineTime);
        SysLogDao sysLogDao = LocalContextFactory.getInstance().getBean(SysLogDao.class);
        SysLog systemLog = new SysLog();
        systemLog.setRealName(user.getRealName());
        systemLog.setLoginName(user.getLoginName());
        systemLog.setDateAdd(new Date());
        systemLog.setName("正常退出系统(" + sessionId + ")，在线时长：" + onLineTime);
        systemLog.setType(SystemLogAnno.LOGOUT);
        user.setEncryptedPassword("***");
        user.setPlainPassword("***");
        systemLog.setParams(JSONObject.toJSONString(user));
        sysLogDao.save(systemLog);
    }

}
